package com.xx.happychatboot.serve.user.service.impl;

import com.xx.happychatboot.serve.user.domain.enums.RoleEnums;
import com.xx.happychatboot.base.vo.response.ResponseDate;
import com.xx.happychatboot.serve.user.domain.entity.SysRole;
import com.xx.happychatboot.serve.user.domain.entity.SysUser;
import com.xx.happychatboot.serve.user.domain.entity.SysUserRole;
import com.xx.happychatboot.serve.user.mapper.SysUserInfoMapper;
import com.xx.happychatboot.serve.user.mapper.SysUserMapper;
import com.xx.happychatboot.serve.user.domain.entity.SysUserInfo;
import com.xx.happychatboot.serve.user.mapper.SysUserRoleMapper;
import com.xx.happychatboot.serve.user.service.ISysRoleService;
import com.xx.happychatboot.serve.user.service.ISysUserService;
import io.mybatis.service.AbstractService;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

@Service
public class SysUserServiceImpl extends AbstractService<SysUser, Long, SysUserMapper> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    public SysUser loadUserByUsername(String username) {
        return sysUserMapper.loadUserByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDate register(SysUser user) {
        if (Objects.isNull(user)
                || StringUtils.isBlank(user.getUsername())
                || StringUtils.isBlank(user.getPassword())) {
            return ResponseDate.fail("遇到错误，请联系管理员");
        }
        String username = new String(Base64.decodeBase64(user.getUsername()));
        String password = new String(Base64.decodeBase64(user.getPassword()));
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ResponseDate.fail("遇到错误，请联系管理员");
        }

        // 对前端传过来的密码加密处理
        String encodePassword = passwordEncoder.encode(password);
        try {
            // 保存sys_user表信息
            SysUser sysUser = SysUser.newUser(username, encodePassword);
            sysUserMapper.insert(sysUser);

            // 保存sys_user_info表信息
            SysUserInfo userInfo = new SysUserInfo();
            userInfo.setUserId(sysUser.getUserId());
            userInfo.setCreateTime(new Date());
            userInfo.setLastOptTime(new Date());
            userInfo.setUpdateTime(new Date());
            sysUserInfoMapper.insert(userInfo);

            // 保存用户角色表信息sys_user_role --- 默认为基本用户
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(sysUser.getUserId());
            sysUserRole.setCreateTime(new Date());
            sysUserRole.setUpdateTime(new Date());
            SysRole role = sysRoleService.selectByRoleCode(RoleEnums.COMMON.getCode());
            if (Objects.isNull(role)) {
                throw new RuntimeException("遇到错误，请联系管理员");
            }
            sysUserRole.setRoleId(role.getRoleId());
            sysUserRoleMapper.insert(sysUserRole);
        } catch (DataIntegrityViolationException e) {
            // 检查异常信息，判断是否是唯一性约束冲突
            if (e.getMostSpecificCause().getMessage().contains("sys_user.UNIQUE_USER_NAME")) {
                return ResponseDate.fail("用户名已存在");
            }
            return ResponseDate.fail("注册失败，数据库错误");
        }

        return ResponseDate.success("注册成功");
    }
}
